package com.tduck.cloud.api.web.ao;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tduck.cloud.account.entity.RoleEntity;
import com.tduck.cloud.account.entity.UserRoleEntity;
import com.tduck.cloud.account.entity.vo.RoleVO;
import com.tduck.cloud.account.entity.vo.UserRoleVo;
import com.tduck.cloud.account.service.RoleService;
import com.tduck.cloud.account.service.UserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色ao
 *
 * @author Guard Baby
 * @date 2023/09/09
 */
@Slf4j
@Service("userRoleAO")
@RequiredArgsConstructor
public class UserRoleAO {
    private final UserRoleService userRoleService;
    private final RoleService roleService;

    @Transactional(rollbackFor = Exception.class)
    public boolean save(UserRoleVo userRoleVo) {
        log.debug("userRoleVo:{}", JSON.toJSONString(userRoleVo));
        QueryWrapper<UserRoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userRoleVo.getUserId());
        userRoleService.remove(queryWrapper);
        List<UserRoleEntity> userRoleEntities = new ArrayList<>();
        for (RoleVO roleVO : userRoleVo.getRoles()) {
            UserRoleEntity userRoleEntity = new UserRoleEntity();
            userRoleEntity.setUserId(userRoleVo.getUserId());
            userRoleEntity.setRoleId(roleVO.getId());
            userRoleEntities.add(userRoleEntity);
        }
        return userRoleService.saveBatch(userRoleEntities);
    }

    public UserRoleVo listByUserId(Long userId) {
        List<UserRoleEntity> userRoleEntities = userRoleService.query().eq("user_id", userId).list();
        if (CollUtil.isNotEmpty(userRoleEntities)) {
            List<RoleEntity> roleEntities = roleService.getBaseMapper().selectBatchIds(userRoleEntities.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList()));
            UserRoleVo userRoleVo = new UserRoleVo();
            userRoleVo.setUserId(userId);
            userRoleVo.setRoles(BeanUtil.copyToList(roleEntities, RoleVO.class));
            return userRoleVo;
        }
        return null;
    }

}
